//
//  UCPickerView.m
//  HelloCall
//
//  Created by WangYongpeng on 13-8-17.
//
//

#import "HCPickerView.h"


@interface HCPickerView()<UIPickerViewDelegate>
{
    struct CGRect    m_rect;
    
	
    NSMutableArray	*m_itemList;
    
	UIPickerView	*m_pickerView;
	UIToolbar		*m_buttonBar;
    
    int				m_nCurSelIndex;
    
	id				m_parentDelegate;
    SEL				m_selector;
	bool            m_tempShakeControl;  //anthzhu adds at 2010-05-04 主题动态切换
	bool m_boxIsClosed; // 窗口是否已经关闭
}

@property (nonatomic, retain) NSString* settingItemID;

@end

@implementation HCPickerView

@synthesize delegate = m_delegate;
@synthesize settingItemID = m_settingItemID;

-(id)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame])!=nil)
    {
		m_rect = frame;
		m_pickerView = [self createPickerView];
		m_buttonBar = [[ self buttonBar ] retain];
		
		[self addBackGroundView:[m_pickerView frame]];
		[self addSubview: m_pickerView];
		[self addSubview: m_buttonBar];
		
        
        m_itemList = [ [ NSMutableArray alloc ] init ];
        
        m_nCurSelIndex = 0;
        m_parentDelegate= nil;
        m_boxIsClosed = false;
        
        [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth];
        [self setAutoresizesSubviews:YES];
        
        self.userInteractionEnabled = YES;
    }
    return self;
}

int	getRotateAngel(const CGRect rect)
{
	if(rect.size.width > rect.size.height)
	{
		return 90;
	}
	return 0;
}

CGSize  getComBoxSize(int rotate)
{
	if(rotate !=0 && rotate != 90)
	{
		rotate = 0;
	}
	
	if(rotate ==0 )
	{
		return  CGSizeMake(320.0,325);
	}
	else
	{
		return CGSizeMake(480.0,170.0);
	}
}

- (id)createPickerView
{
	CGSize size = getComBoxSize(getRotateAngel(m_rect));
	UIPickerView* pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, m_rect.size.height-size.height, m_rect.size.width, size.height)];
//	CGSize pickerSize = [pickerView sizeThatFits:CGSizeZero];
//	if(!CGSizeEqualToSize(pickerSize, size))
//	{
//		pickerView.frame = CGRectMake(0, m_rect.size.height-pickerSize.height, m_rect.size.width, pickerSize.height);
//	}
    
	pickerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	pickerView.delegate = self;
	pickerView.showsSelectionIndicator = YES;	// note this is default to NO
	return pickerView;
}

//index: zero based !
- (BOOL)initDataWithData:(NSMutableArray*)data curSel:(int)index
{
	if(data == nil)
	{
        assert(0);
		return NO;
	}
    
    //If empty, add a "none" to it to To avoid UIPicker crash.(IOS bug)
    if ([data count] == 0)
    {
        [data addObject:@"无"];
    }
    
	if(index >= [ data count ] || index < 0)
	{
        assert(0);
		return NO;
	}
	m_nCurSelIndex = index;
    
	[m_itemList removeAllObjects];
    for(int i=0;i<[ data count ];i++)
    {
		[ m_itemList addObject: [ data objectAtIndex: i ]  ];
    }
    
	[m_pickerView selectRow: m_nCurSelIndex inComponent: 0 animated: NO];
	return YES;
}

-(void)pickerViewLoaded: (UIPickerView*)pickerView
{
    
}


- (void)setSelectorWithDelegate:(SEL)selector withDelegate:(id)parent
{
	m_parentDelegate = parent;
	m_selector		 = selector;
}

- (int) numberOfColumnsInPickerView:(id)pickerView
{
    return 1;
}

- (int) pickerView:(id)pickerView numberOfRowsInColumn:(int)col
{
    return [ m_itemList count ];
}

- (void)onClose
{
	CGRect frame = self.frame;
	[UIView beginAnimations:@"close" context:nil];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDuration: 0.3];
	self.frame = CGRectMake(frame.origin.x, [UIScreen mainScreen].bounds.size.height, frame.size.width, frame.size.height);
	[UIView commitAnimations];
}


- (id )buttonBar
{
	NSArray *array	= [ self buttonBarItems ];
	CGSize size = CGSizeMake(m_rect.size.width, 40);
	UIToolbar *toolbar	= [[[UIToolbar alloc] initWithFrame:CGRectMake(0.0f, m_pickerView.frame.origin.y-size.height, m_rect.size.width, size.height)] autorelease] ;
	toolbar.barStyle	= UIBarStyleBlackOpaque;//UIBarStyleDefault;
	
	CGSize toolsize = [toolbar sizeThatFits:CGSizeZero];
	if(!CGSizeEqualToSize(toolsize, size))
	{
		toolbar.frame = CGRectMake(0.0f, m_pickerView.frame.origin.y-toolsize.height, m_rect.size.width, toolsize.height);
	}
	[toolbar sizeToFit];
	toolbar.items =  array;
	return toolbar;
}

- (void)buttonBarItemTapped:(id)sender
{
	if (m_boxIsClosed)
	{
		return;
	}
	m_boxIsClosed = true;
	[[UIApplication sharedApplication] beginIgnoringInteractionEvents];	//zds add 2010-02-02,fixbug:24925
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(onTimer:) userInfo: nil repeats:NO];
	[pool release];
}

- (void)onTimer:(NSTimer *)sender
{
	if([sender isValid ])
	{
		[sender invalidate];
	}
	
	[[UIApplication sharedApplication] endIgnoringInteractionEvents];

    [self onClose];
}

- (NSArray *)buttonBarItems
{
	UIBarButtonItem *buttonFinish = [[UIBarButtonItem alloc] initWithTitle:@"完成"
                                                                     style:UIBarButtonItemStyleBordered
                                                                    target:self
                                                                    action:@selector(buttonBarItemTapped:)];
	[buttonFinish setTag:1];
	
	UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                              target:nil
                                                                              action:nil];
	
	NSArray *array = [NSArray arrayWithObjects: flexItem,buttonFinish, (id)nil];
	[flexItem release];
	[buttonFinish release];
	return array;
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	//[m_itemList objectAtIndex:[pickerView selectedRowInComponent:0]
	m_nCurSelIndex = row;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	return [m_itemList objectAtIndex:row];
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	return m_rect.size.width;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
	return 40.0;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return [m_itemList count];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}


- (void)dealloc
{
    
    m_pickerView.delegate = nil;
	[m_pickerView removeFromSuperview];
	[m_pickerView release];
	m_pickerView = nil;
	[m_buttonBar removeFromSuperview ];
	[m_buttonBar release];
	m_buttonBar = nil;
	[m_itemList removeAllObjects];
	[m_itemList release];
	m_itemList = nil;
    self.settingItemID = nil;
	
	[super dealloc];
}

//parentView:父窗体，data:数据，cmd：命令，可以设置为相应时发出的命令，默认为0
-(void)addSuperView:(UIView*)parentView data:(NSArray*)dataArray currentSel:(int)currentSel settingItemName:(NSString*)itemName
{
	if(parentView == nil)
	{
		return;
	}
    
    self.settingItemID = itemName;
    
    [self retain];   ///<修改：对当前view进行一次retain.保证在其声明周期内retianCount值不为0.liuqina, 2013/01/08
    
	NSString *text = nil;

	NSMutableArray *itemList = [ [ NSMutableArray alloc ] init ];
	for(int i=0; i<dataArray.count ;i++)
	{
		text = [dataArray objectAtIndex:i];
		if (text != nil)
		{
			[itemList addObject: text];
		}
	}
	
	[self initDataWithData: itemList curSel:currentSel ];
	[itemList release];
    
	[parentView addSubview: self];
	
	
	CGRect frame = self.frame;
	self.frame = CGRectMake(frame.origin.x, [UIScreen mainScreen].bounds.size.height, frame.size.width, frame.size.height);
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDuration: 0.3];
	
	self.frame = frame;
	[UIView commitAnimations];
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
	CGRect rect;
	rect.origin = m_buttonBar.frame.origin;
	rect.size.width = m_buttonBar.frame.size.width;
	rect.size.height= self.frame.size.height- m_buttonBar.frame.origin.y;
	if(CGRectContainsPoint(rect, point))
	{
		return TRUE;
	}
	else
	{
		// 点击在窗口之外时,要关闭窗口
		if (m_boxIsClosed)
		{
			// fixbug: 0083927: 切换浏览模式时,点击"完成"后,迅速点击地址输入框,系统崩溃退出
			return FALSE;
		}
		m_boxIsClosed = true;
	}
	
	//anthhzu adds at 2010-05-04 主题动态切换
    [self onClose];
	return FALSE;
}

///< 动画结束
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
	if ([animationID isEqualToString:@"close"])
	{
        if ([self.delegate respondsToSelector:@selector(userSelectedIndex:settingItemName:)])
        {
            [self.delegate userSelectedIndex:m_nCurSelIndex settingItemName:self.settingItemID];
        }
        
//		[self onDisappear];
		[self removeFromSuperview];
		[self release];
	}
}

float iGetSystemVersion()
{
	static float versionValue = -1.0;
	if(versionValue < 0.f)
	{
		NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
		NSString *os_verson = [[UIDevice currentDevice] systemVersion];
		
		// 处理形如6.1.3的版本号，使其变成6.13，方便外部处理
		NSArray* versionNumbers = [os_verson componentsSeparatedByString:@"."];
		os_verson = @"";
		for (int i = 0; i < versionNumbers.count; i++)
		{
			os_verson = [os_verson stringByAppendingString:[versionNumbers objectAtIndex:i]];
			if (i == 0)
			{
				os_verson = [os_verson stringByAppendingString:@"."];
			}
		}
		
		versionValue = [os_verson floatValue];
		[pool release ];
	}
	return versionValue;
}

- (void)addBackGroundView:(CGRect)rect
{
#ifdef __IPHONE_7_0
	// ios 6.X及以下版本OK,不需要处理
	float version = iGetSystemVersion();
    
	if(version > 6.9 && version < 8.0)
    {
		// ios7 版本
        // UIPickerView视图下方的背景视图
		UIView* pBackGroundView = nil;
		pBackGroundView = [[UIView alloc] initWithFrame:rect];
		pBackGroundView.backgroundColor = [UIColor whiteColor];
		[self addSubview:pBackGroundView];
		[pBackGroundView release];
		
		// 工具栏下方的背景
		pBackGroundView = [[UIView alloc] initWithFrame:[m_buttonBar frame]];
		pBackGroundView.backgroundColor = [UIColor blackColor];
		[self addSubview:pBackGroundView];
		[pBackGroundView release];
		
		// 工具栏文字颜色
		m_buttonBar.tintColor = [UIColor whiteColor];
    }
#endif
}

@end



